package com.xiaoke.exception;

import com.xiaoke.domain.R;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * DTO参数异常验证处理
     * @param e 异常类
     * @return 错误信息
     */
    @ExceptionHandler(BindException.class)
    public R<String> methodArgumentNotValidException(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        //获取验证错误信息集合
        List<String> messages = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        //只提示一条
        return R.error(messages.get(0));
    }

}
